<template>
    <div class="todo-container">
    <div class="todo-wrap">
      <!-- <Header @addtodo="addtodo" /> -->
      <Header ref="header"/>
      <List :todos="todos"/>
      <Footer :todos ="todos" :checkAlltodo="checkAlltodo" :deleteAll="deleteAll"/>
      <button @click="$refs.header.$off('addtodo')">解绑事件</button>
      <button @click="$mitt.off('checkTodo')">解绑事件</button>
      <button @click="$bus.$off('deleteTodo')">解绑事件</button>
    </div>
  </div>

</template>

<script>
import Header from './components/Header/index.vue'
import List from './components/List/index.vue'
import Footer from './components/Footer/index.vue'

import {nanoid} from 'nanoid'

export default {
    name:'App',
    components:{
        Header,
        List,
        Footer
    },
    data(){
      return {
      //   todos:[
      //   {id: '001', title: '看科比打球', done: false},
      //   {id: '002', title: '听许巍的演唱会', done: false},
      //   {id: '003', title: '挣它100万', done: true},
      // ]
      todos:[]
      }
    },
    watch:{
      todos:{
        handler(val){
          localStorage.setItem('todos_key',JSON.stringify(val))
        },
        deep:true
      }
    },

    mounted(){
      console.log(this.$refs.header);
      
      this.$refs.header.$on('addtodo',this.addtodo)

      setTimeout(()=>{
        this.todos = JSON.parse(localStorage.getItem('todos_key')) || []
      },1000)

      this.$bus.$on('deleteTodo',this.deleteTodo)

      this.$mitt.on('checkTodo',this.checkTodo)
    },

    beforeDestroy(){
      // this.$bus.$off('deleteTodo')

      this.$mitt.off('checkTodo',this.checkTodo)
    },

    methods:{
      addtodo(title){

        const todo = {
          id: nanoid(),
          title,
          done:false
        }

        this.todos.unshift(todo)

      },
      deleteTodo(index){
        this.todos.splice(index,1)
      },
      checkTodo({todo,isCheck}){
        todo.done = isCheck
      },
      checkAlltodo(done){
        this.todos.forEach((todo)=>{
          todo.done = done
        })
      },
      deleteAll(){
        const flit = this.todos.filter((todo)=>!todo.done)
        this.todos = flit
      }
    }
}
</script>

<style>
    .todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>